package org.jeecgframework.web.service.impl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.service.impl.CommonServiceImpl;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyPlanRecordServiceI;
import org.jeecgframework.web.system.pojo.base.TSType;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.pojo.base.ZyPlanRecordEntity;
import org.jeecgframework.web.system.pojo.base.zyPlanStateProcessBean;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("zyPlanRecordService")
@Transactional
public class ZyPlanRecordServiceImpl extends CommonServiceImpl implements ZyPlanRecordServiceI {

	@Autowired
	private ZyCommonService zyCommonService;
	
 	public <T> void delete(T entity) {
 		super.delete(entity);
 		//执行删除操作配置的sql增强
		this.doDelSql((ZyPlanRecordEntity)entity);
 	}
 	
 	public <T> Serializable save(T entity) {
 		Serializable t = super.save(entity);
 		//执行新增操作配置的sql增强
 		this.doAddSql((ZyPlanRecordEntity)entity);
 		return t;
 	}
 	
 	public <T> void saveOrUpdate(T entity) {
 		super.saveOrUpdate(entity);
 		//执行更新操作配置的sql增强
 		this.doUpdateSql((ZyPlanRecordEntity)entity);
 	}
 	
 	/**
	 * 默认按钮-sql增强-新增操作
	 * @param id
	 * @return
	 */
 	public boolean doAddSql(ZyPlanRecordEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-更新操作
	 * @param id
	 * @return
	 */
 	public boolean doUpdateSql(ZyPlanRecordEntity t){
	 	return true;
 	}
 	/**
	 * 默认按钮-sql增强-删除操作
	 * @param id
	 * @return
	 */
 	public boolean doDelSql(ZyPlanRecordEntity t){
	 	return true;
 	}
 	
 	/**
	 * 替换sql中的变量
	 * @param sql
	 * @return
	 */
 	public String replaceVal(String sql,ZyPlanRecordEntity t){
 		sql  = sql.replace("#{id}",String.valueOf(t.getId()));
 		sql  = sql.replace("#{bus_id}",String.valueOf(t.getBusId()));
 		sql  = sql.replace("#{proc_ins_id}",String.valueOf(t.getProcInsId()));
 		sql  = sql.replace("#{task_id}",String.valueOf(t.getTaskId()));
 		sql  = sql.replace("#{remark}",String.valueOf(t.getRemark()));
 		sql  = sql.replace("#{UUID}",UUID.randomUUID().toString());
 		return sql;
 	}

	public List<zyPlanStateProcessBean> queryPlanStateProcess(String zyPlanId) {
		//先查询是否有取消巡检计划的状态
		int countCancel = zyCommonService.getCountBySql("SELECT COUNT(1) AS total FROM zy_plan_record pr WHERE pr.bus_id = '"+zyPlanId+"' AND pr.plan_state = '"+StaticValue.DIC_PLAN_STATE_INSPECTION_CANCEL+"'");
		Criteria c = getSession().createCriteria(ZyPlanRecordEntity.class);
		c.add(Restrictions.eq("busId", zyPlanId));
		c.addOrder(Order.desc("createDate"));
		List<ZyPlanRecordEntity> zyPlanRecordList = c.list();
		List<zyPlanStateProcessBean> planStates = new ArrayList<zyPlanStateProcessBean>();
		
		TSType tsType = zyCommonService.queryTsType(StaticValue.DIC_PLAN_STATE, StaticValue.DIC_PLAN_STATE_TODO);
		planStates.add(new zyPlanStateProcessBean(StaticValue.DIC_PLAN_STATE_TODO,null != tsType ? tsType.getTypename() : ""));
		
		tsType = zyCommonService.queryTsType(StaticValue.DIC_PLAN_STATE, StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY);
		planStates.add(new zyPlanStateProcessBean(StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY,null != tsType ? tsType.getTypename() : ""));//已分配第三方，特殊点 存在拒绝
		
		tsType = zyCommonService.queryTsType(StaticValue.DIC_PLAN_STATE, StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED);
		planStates.add(new zyPlanStateProcessBean(StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED,null != tsType ? tsType.getTypename() : ""));//第三方已分配，特殊点 存在拒绝
		
		tsType = zyCommonService.queryTsType(StaticValue.DIC_PLAN_STATE, StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED);
		planStates.add(new zyPlanStateProcessBean(StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED,null != tsType ? tsType.getTypename() : ""));//区域工程师已分配，特殊点 存在拒绝
		
		tsType = zyCommonService.queryTsType(StaticValue.DIC_PLAN_STATE, StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED);
		planStates.add(new zyPlanStateProcessBean(StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED,null != tsType ? tsType.getTypename() : ""));
		
		tsType = zyCommonService.queryTsType(StaticValue.DIC_PLAN_STATE, StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT);
		planStates.add(new zyPlanStateProcessBean(StaticValue.DIC_PLAN_STATE_ENGINEER_IN_IMPLEMENT,null != tsType ? tsType.getTypename() : ""));
		
		tsType = zyCommonService.queryTsType(StaticValue.DIC_PLAN_STATE, StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE);
		planStates.add(new zyPlanStateProcessBean(StaticValue.DIC_PLAN_STATE_INSPECTION_COMPLETE,null != tsType ? tsType.getTypename() : ""));
		if(countCancel > 0){
			planStates.get(0).setIsComplete(false);
			planStates.get(1).setIsComplete(false);
			planStates.get(2).setIsComplete(false);
			planStates.get(3).setIsComplete(false);
			planStates.get(4).setIsComplete(false);
			planStates.get(5).setIsComplete(false);
			planStates.get(6).setIsComplete(false);
		}else{
			for (zyPlanStateProcessBean planStateBean : planStates) {
				tsType = zyCommonService.queryTsType(StaticValue.DIC_PLAN_STATE, planStateBean.getStateCode());
				planStateBean.setStateVal(null != tsType ? tsType.getTypename() : "");
				for (ZyPlanRecordEntity zyPlanRecord : zyPlanRecordList) {
					if(planStateBean.getStateCode().equals(zyPlanRecord.getPlanState())){
						planStateBean.setIsComplete(true);
						break;
					}
				}
			}
			List<Map<String, Object>> countStatesMapList = 
					findForJdbc("SELECT COUNT(plan_state) AS total,plan_state FROM zy_plan_record WHERE bus_id = ? AND !ISNULL(plan_state) GROUP BY plan_state ",zyPlanId);
			
			int countBarcoForward = 0,countTPBack = 0;//巴可 节点，巴可分配次数大于第三方拒绝次数。就是绿色的
			int countTpForward = 0,countAegBack = 0;//第三负责人方节点，第三方负责人分配次数大于 区域工程师or工程师拒绝次数。就是绿色的
			int countAegForward = 0,countEgBack = 0;//第三方区域节点，区域工程师分配次数大于工程师拒绝次数。就是绿色的
			boolean egForWard = false;//工程师只要接受了。就是绿色的
			
			for (Map<String, Object> stateCountMap : countStatesMapList) {
				int count = Integer.valueOf(stateCountMap.get("total").toString());
				String planState = stateCountMap.get("plan_state").toString();
				if(planState.equals(StaticValue.DIC_PLAN_STATE_SEND_TO_THIRDPARTY)){
					countBarcoForward = count;
				}else if(planState.equals(StaticValue.DIC_PLAN_STATE_THIRDPARTY_ASSIGNED)){
					countTpForward = count;
				}else if(planState.equals(StaticValue.DIC_PLAN_STATE_THIRDPARTY_REFUSED)){
					countTPBack = count;
				}else if(planState.equals(StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_ASSIGNED)){
					countAegForward = count;
				}else if(planState.equals(StaticValue.DIC_PLAN_STATE_AREA_ENGINEER_REFUSED)){
					countAegBack = count;
				}else if(planState.equals(StaticValue.DIC_PLAN_STATE_ENGINEER_ASSIGNED)){
					egForWard = true;
				}else if(planState.equals(StaticValue.DIC_PLAN_STATE_ENGINEER_REFUSED)){
					countEgBack = count;
				}
			}
			planStates.get(1).setIsComplete(countBarcoForward >= countTPBack  && countBarcoForward != 0 ? true : false);
			/**
			 * 如果工程师已经接受任务，并且没有区域工程师操作的痕迹，那么认为没有区域工程师。
			 * 此时第三方节点的判断需要跟据工程师拒绝和第三方分配判断
			 */
			if(countAegForward == 0 && countAegBack == 0 && !egForWard){
				planStates.get(2).setIsComplete(countTpForward > countEgBack  && countTpForward != 0 ? true : false);
			}else{
				planStates.get(2).setIsComplete(countTpForward > countAegBack  && countTpForward != 0 ? true : false);
			}
			planStates.get(3).setIsComplete(countAegForward > countEgBack && countAegForward != 0 ? true : false);
			planStates.get(4).setIsComplete(egForWard);
		}
		
		
		return planStates;
	}
	
	
	public ZyPlanRecordEntity savePlanRecord(String busId,String procInsId,String taskId,String planState,String userName,String remark){
		ZyPlanRecordEntity record = new ZyPlanRecordEntity();
		record.setTaskId(taskId);
		record.setPlanState(planState);
		record.setProcInsId(procInsId);
		record.setRemark(remark);
		record.setBusId(busId);
		if(StringUtil.isNotEmpty(userName)){
			TSUser user = this.findUniqueByProperty(TSUser.class, "userName", userName);
			record.setTsUser(user);
		}
		this.save(record);
		return record;
	}
	
	
	
	
	
}